<template>
  <div class="AdvancedSearchsPlus">
    <div class="retrieval" v-if="props.label === '检索'">
      <div class="data-info">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="basic-search">
        <el-input placeholder="请输入" v-model="state.input" class="input-with-select">
          <template #prepend>
            <el-select v-model="state.select" placeholder="请选择">
              <el-option v-for="item of searchFields" :label="item.label" :key="item.value" :value="item.value"></el-option>
            </el-select>            
          </template>
        </el-input>

        <div class="wrapper">
          <el-button v-show="!state.searchList.length" :icon="Plus" @click="handleAdd"></el-button>
        </div>
      </div>

      <div class="searchList">
        <div v-for="(item, index) of state.searchList" :key="index" class="searchList-item">
          <div class="relationship">
            <el-select v-model="item.relationshipFake" placeholder="请选择">
              <el-option v-for="item of state.relationshipList" :label="item.label" :key="item.value" :value="item.value"></el-option>
            </el-select>
          </div>
          <el-input placeholder="请输入" v-model="item.input" class="input-with-select">
            <template #prepend>
              <el-select v-model="item.select" slot="prepend" placeholder="请选择">
                <el-option v-for="item of searchFields" :label="item.label" :key="item.value" :value="item.value"></el-option>
              </el-select>              
            </template>
          </el-input>
          <div class="btn-group" v-if="index === state.searchList.length - 1">
            <el-button :icon="Plus" @click="handleAdd()"></el-button>
            <el-button :icon="Minus" @click="handleReduce(index)"></el-button>
          </div>
          <div class="btn-group" v-else>
            <el-button icon="el-icon-minus" @click="handleReduce(index)"></el-button>
          </div>
        </div>
      </div>

      <div class="notes">
        <el-input placeholder="请输入备注" v-model="state.notes" />
      </div>

      <div class="btn-grp">
        <el-button @click="searchResult" type="primary">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>

    <div class="association" v-else-if="label === '关联'">
      <div class="data-slect">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>

      <div class="data-slect">
        <el-select v-model="state.association" @change="handleAssociationChange" placeholder="请选择关联对象">
          <el-option
            v-for="item in searchFields"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      <div class="data-input">
        <el-input :placeholder="state.associationPlaceholder" v-model="state.associationvalue" />
      </div>

      <div class="notes">
        <el-input placeholder="请输入备注" v-model="state.notes" />
      </div>

      <div class="btn-grp">
        <el-button @click="associationResult" type="primary">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>

    <div v-else-if="label === '遍历'">
      <div class="ergodic">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-select v-model="state.ergodic" placeholder="请选择遍历字段">
          <el-option
            v-for="item in searchFields"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>

        <el-input placeholder="请输入备注" v-model="state.notes" />

        <div class="btn-grp">
          <el-button @click="ergodicResult" type="primary">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>

      <!-- <div class="nodata" v-else>暂无历史数据</div> -->
    </div>

    <div v-else-if="label === '排序'">
      <div class="sort">
        <div class="sort-item">
          <el-select v-model="state.ret" placeholder="请选择数据集">
            <el-option
              v-for="item in state.retList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>

        <div class="sort-item">
          <el-select v-model="state.sortType" placeholder="请选择排序字段">
            <el-option
              v-for="item in searchFields"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>

        <div class="sort-item">
          <el-select v-model="state.sortOrder" placeholder="请选择升降序">
            <el-option label="升序" value="升序"></el-option>
            <el-option label="降序" value="降序"></el-option>
          </el-select>
        </div>

        <div class="sort-item">
          <el-input placeholder="请输入备注" v-model="state.notes" />
        </div>

        <div class="btn-grp">
          <el-button @click="sortResult" type="primary">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>

      <!-- <div class="nodata" v-else>暂无历史数据</div> -->
    </div>

    <div class="condition" v-else-if="label === '条件'">
      <div class="data-info">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
      <div class="mid">
        <el-select v-model="state.conditionField" placeholder="请选择字段">
          <el-option v-for="item of searchFields" :label="item.label" :key="item.value" :value="item.value"></el-option>
        </el-select>
        <el-select v-model="state.conditionSymbol" placeholder="请选择条件">
          <el-option label="等于" value="等于"></el-option>
          <el-option label="不等于" value="不等于"></el-option>
          <el-option label="包含" value="包含"></el-option>
          <el-option label="不包含" value="不包含"></el-option>
        </el-select>
        <el-input placeholder="请输入具体数值" v-model="state.conditionValue" class="input-with-select"></el-input>
      </div>

      <div class="notes">
        <el-input placeholder="请输入备注" v-model="state.notes" />
      </div>

      <div class="btn-grp">
        <el-button @click="conditionResult" type="primary">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </div>

    <div v-else-if="label === '统计'">
      <div class="count" >
        <div class="data-info">
          <el-select v-model="state.ret" placeholder="请选择数据集">
            <el-option
              v-for="item in state.retList"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <el-input placeholder="请输入" v-model="state.countValue" class="input-with-select">
          <template #prepend>
            <el-select v-model="state.count" placeholder="请选择">
              <el-option v-for="item of searchFields" :label="item.label" :key="item.value" :value="item.value"></el-option>
            </el-select>            
          </template>
        </el-input>
        <div class="notes">
          <el-input placeholder="请输入备注" v-model="state.notes" />
        </div>
        <div class="btn-grp">
          <el-button @click="countResult" type="primary">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>

      <!-- <div class="nodata" v-else>暂无历史数据</div> -->
    </div>

    <div v-else-if="label === '最大值'">
      <div class="max-min">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-input placeholder="请输入备注" v-model="state.notes" />

        <div class="btn-grp">
          <el-button @click="maxResult" type="primary">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
      <!-- <div class="nodata" v-else>暂无历史数据</div> -->
    </div>

    <div v-else-if="label === '最小值'">
      <div class="max-min">
        <el-select v-model="state.ret" placeholder="请选择数据集">
          <el-option
            v-for="item in state.retList"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
        </el-select>

        <el-input placeholder="请输入备注" v-model="state.notes" />

        <div class="btn-grp">
          <el-button @click="minResult" type="primary">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </div>
      <!-- <div class="nodata" v-else>暂无历史数据</div> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import { Plus, Minus } from "@element-plus/icons-vue";
import { watch } from "vue";

const props = defineProps({
  searchFields: {
    type: [Array, Object],
    default: () => {
      return []
    }
  },
  width: {
    type: [Number, String],
    default: 80
  },
  label: {
    type: String,
    default: ''
  }
})

watch(
  () => props.searchFields,
  () => {
    // 检索
    state.input = ''

    // 关联
    state.association = '文件'
    state.associationvalue = ''
    state.associationPlaceholder = '请输入MD5'
    state.aKey = 'MD5'

    if (props.searchFields && props.searchFields.length) state.select = (props.searchFields as any)[0].value
    state.searchList = []
    state.notes = ''
    state.ret = ''

    // 遍历
    state.ergodic = ''

    // 排序
    state.sortType = ''
    state.sortOrder = ''

    // 条件
    state.conditionValue = ''
    state.conditionField = ''
    state.conditionSymbol = ''

    // 统计
    state.count = ''
    state.countValue = ''
  }
)

interface mapEmit {
  (e:string, v:any): void
}
const emit = defineEmits<mapEmit>()

interface asp {
  // 检索、关联
  input:string,
  select:string,
  searchList:Array<any>,
  relationshipList:Array<any>,

  // 关联
  association:string,
  associationvalue:string,
  associationPlaceholder:string,
  aKey:string,

  notes:string,

  ret_num: 0,
  retList:Array<any>,
  ret:string, // 每次都要清除

  // 遍历
  ergodic:string,

  // 排序
  sortType:string,
  sortOrder:string,

  // 条件
  conditionValue:string,
  conditionField:string,
  conditionSymbol:string,

  // 统计
  count:string,
  countValue:string
}

const state = reactive<asp>({
  // 检索、关联
  input: '',
  select: '',
  searchList: [],
  relationshipList: [
    {
      label: 'AND',
      value: '&&'
    },
    {
      label: 'OR',
      value: '||'
    },
    {
      label: 'NOT',
      value: '&&!'
    }
  ],

  // 关联
  association: '文件',
  associationvalue: '',
  associationPlaceholder: '请输入MD5',
  aKey: 'MD5',

  notes: '',

  ret_num: 0,
  retList: ['初始数据集'],
  ret: '', // 每次都要清除

  // 遍历
  ergodic: '',

  // 排序
  sortType: '',
  sortOrder: '',

  // 条件
  conditionValue: '',
  conditionField: '',
  conditionSymbol: '',

  // 统计
  count: '',
  countValue: ''
})

onMounted(() => {
    // 检索、检索
    state.input = ''

    // 关联
    state.association = '文件'
    state.associationvalue = ''
    state.associationPlaceholder = '请输入MD5'
    state.aKey = 'MD5'

    if (props.searchFields && props.searchFields.length) state.select = (props.searchFields as any)[0].value
    state.searchList = []
    state.notes = ''
    state.ret = ''

    // 遍历
    state.ergodic = ''

    // 排序
    state.sortType = ''
    state.sortOrder = ''

    // 条件
    state.conditionValue = ''
    state.conditionField = ''
    state.conditionSymbol = ''

    // 统计
    state.count = ''
    state.countValue = ''
})

// 检索
const handleAdd = () => {
  state.searchList.push({
    select: '',
    input: '',
    relationship: '&&',
    relationshipFake: ''
  })
  nextTick(() => {
    let doms:any = document.querySelectorAll('.el-input-group__prepend')
    doms = [...doms]
    doms.forEach((i:any) => {
      i.style.width = props.width + 'px'
    })
  })
}
const handleReduce = (index:any) => {
  state.searchList.splice(index, 1)
}
const searchResult = () => {
  const notes = state.notes ? '// ' + state.notes + '\n' : ''
  if (state.searchList.length) {
    const temp = JSON.stringify(state.searchList)
    const index = temp.indexOf('\"\"')
    if (index === -1 && state.input && state.select && state.searchList.length) {
      state.ret_num++
      state.retList.push('RET' + state.ret_num)
      const result = handleData()
      const res = '结果RET' + state.ret_num + "=【会话数据集合】；"
      const codeString = notes + props.label + '【' + result.substring(0, result.length - 1) + '】，' + res
      emit('savestep', codeString)
    } else {
      ElMessage({
        type: 'warning',
        message: '请输入完整的信息'
      })
    }
  } else {
    if (state.input && state.select) {
      state.ret_num++
      state.retList.push('RET' + state.ret_num)
      const signlItem = props.searchFields.find((i:any) => {
        return i.value === state.select 
      })
      const res = '结果RET' + state.ret_num + "=【会话数据集合】；"
      const codeString = notes + props.label + '【' + signlItem.label + '= ' + state.input + '】，' + res
      emit('savestep', codeString)
    } else {
      ElMessage({
        type: 'warning',
        message: '请输入完整的信息'
      })
    }
  }
}
const handleData = () => {
  const searchFields = props.searchFields
  function innerMethod (data:any, relationship:any) {
    if (data && data.length) {
      let temp = ''

      const groupObject = data.reduce((acc:any, cur:any) => {
          if (!acc[cur.select]) {
            acc[cur.select] = []
          }
          acc[cur.select].push(cur)
          return acc
      }, {})

      for (const key in groupObject) {
        const valueArr = groupObject[key].map((i:any) => {
          return i.input
        })
        const item = searchFields.find((i:any) => {
          return i.value === key
        })
        temp += item.label + '= ' + valueArr.join(',') + '，'
      }
      return temp
    } else {
      return []
    }
  }

  const ANDList = state.searchList.filter((i:any) => {
    return i.relationship === '&&'
  })
  ANDList.unshift({
    select: state.select,
    input: state.input,
    relationship: '&&'
  })

  const ORList = state.searchList.filter(i => {
    return i.relationship === '||'
  })

  const NOTList = state.searchList.filter(i => {
    return i.relationship === '&&!'
  })

  const ANDString:any = innerMethod(ANDList, '&&')
  const ORString:any = innerMethod(ORList, '||')
  const NOTString:any = innerMethod(NOTList, '&&!')

  return ANDString + ORString + NOTString
}

// 关联
const associationResult = () => {
  if (state.association && state.associationvalue && state.ret) {
    state.ret_num++
    state.retList.push('RET' + state.ret_num)
    const notes = state.notes ? '// ' + state.notes + '\n' : ''
    const codeString = notes + props.label + '【' + state.ret + '，' + '关联对象= ' +
    state.association + '，' +  state.aKey + '= ' + state.associationvalue + '】，' + 
    '结果RET' + state.ret_num + '=【会话数据集合' + '】；'
    emit('savestep', codeString)
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入完整的信息'
    })
  }
}
const handleAssociationChange = (value:any) => {
  switch (value) {
    case '文件':
      state.aKey = 'MD5'
      state.associationPlaceholder = '请输入MD5'
      break
    default:
      state.aKey = value
      state.associationPlaceholder = '请输入' + state.aKey
  }
}

// 遍历
const ergodicResult = () => {
  if (state.ret && state.ergodic) {
    const ergodicItem = props.searchFields.find((i:any) => {
      return i.value === state.ergodic
    })
    const notes = state.notes ? '// ' + state.notes + '\n' : ''
    const codeString = notes + props.label + '【' + state.ret + '，' + ergodicItem.label +  '】；' 
    emit('savestep', codeString)
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入完整的信息'
    })
  }
}

// 排序
const sortResult = () => {
  if (state.sortType && state.sortOrder) {
    state.ret_num++
    state.retList.push('RET' + state.ret_num)
    const sortItem = props.searchFields.find((i:any) => {
      return i.value === state.sortType
    })
    const notes = state.notes ? '// ' + state.notes + '\n' : ''
    const codeString = notes + props.label + '【'+ sortItem.label + '，' + state.sortOrder + '】，' + '结果' + 'RET' + state.ret_num + '=【会话数据集合' + '】；'
    emit('savestep', codeString)
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入完整的信息'
    })
  }
}

// 条件
const conditionResult = () => {
  if (state.conditionValue && state.conditionField && state.conditionSymbol) {
    const notes = state.notes ? '// ' + state.notes + '\n' : ''
    const conditionItem = props.searchFields.find((i:any) => {
      return i.value === state.conditionField
    })
    const codeString = notes + props.label + `【${conditionItem.label + state.conditionSymbol + state.conditionValue}】；`
    emit('savestep', codeString)
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入完整的信息'
    })
  }
}

// 统计
const countResult = () => {
  if (state.countValue && state.count) {
    state.ret_num++
    state.retList.push('RET' + state.ret_num)
    const notes = state.notes ? '// ' + state.notes + '\n' : ''
    const countItem = props.searchFields.find((i:any) => {
      return i.value === state.count
    })
    const codeString = notes + props.label + `【${state.ret}，数量】，结果RET${state.ret_num}=【${countItem.label}= ${state.countValue}】；`
    emit('savestep', codeString)
  } else {
    ElMessage({
      type: 'warning',
      message: '请输入完整的信息'
    })
  }
}

// 最大
const maxResult = () => {
  const notes = state.notes ? '// ' + state.notes + '\n' : ''
  const codeString = notes + props.label + `【MAX(${state.ret})】`
  emit('savestep', codeString)
}

// 最小
const minResult = () => {
  const notes = state.notes ? '// ' + state.notes + '\n' : ''
  const codeString = notes + props.label + `【MIN(${state.ret})】`
  emit('savestep', codeString)
}

const cancel = () => {
  emit('canceloperate', null)
}
</script>

<style lang="scss" scoped>
.AdvancedSearchsPlus {
  position: relative;
  // 检索
  .retrieval {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    :deep(.input-with-select) {
      width: 500px;
    }
    :deep(.el-input-group__prepend) {
      background-color: #fff;
      width: 80px;
    }
    .basic-search {
      // padding-left: px;
      margin-left: 42px;
      .wrapper {
        width: 42px;
      }
      display: flex;
      :deep(.el-button) {
        background-color: #ccc;
        color: #fff;
        font-weight: bolder;
        padding: 0 !important;
        width: 32px;
        height: 32px;
        margin-left: 10px;
        .el-icon-plus:before {
          font-weight: 700;
          font-size: 16px;
        }
        .el-icon-minus:before {
          font-weight: 700;
          font-size: 16px;
        }
      }
    }
    .searchList {
      margin-top: 15px;
      // margin-left: 43px;
      margin-right: 17px;
      .searchList-item {
        margin-bottom: 15px;
        display: flex;
        .relationship {
          .el-select {
            width: 90px;
            margin-right: 10px;
          }
        }
        .btn-group {
          margin-left: 10px;
          :deep(.el-button) {
            background-color: #ccc;
            color: #fff;
            font-weight: bolder;
            padding: 0 !important;
            width: 32px;
            height: 32px;
            .el-icon-plus:before {
              font-weight: 700;
              font-size: 16px;
            }
            .el-icon-minus:before {
              font-weight: 700;
              font-size: 16px;
            }
          }
        }
      }
    }

    .notes {
      // margin-right: 38px;
      display: flex;
      margin-bottom: 20px;
      span {
        // width: 40px;
        margin-right: 10px;
        line-height: 32px;
        display: inline-block;
      }
      :deep(.el-input) {
        width: 502px;
      }
    }

    .data-info {
      width: 500px;
      :deep(.el-select) {
        width: 100%;
        margin-bottom: 15px;
      }
    }

    .btn-grp {
      width: 66%;
      text-align: right;
    }
  }
  // 关联
  .association {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .data-slect {
      :deep(.el-select) {
        width: 300px;
        margin-bottom: 15px;
      }
    }
    .data-input {
      margin-bottom: 15px;
      :deep(.el-input) {
        width: 300px;
      }
    }
    .notes {
      margin-bottom: 15px;
      :deep(.el-input) {
        width: 300px;
      }
    }
    .btn-grp {
      text-align: right;
      width: 300px;
    }
  }
  // 遍历
  .ergodic {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 40px;
    box-sizing: border-box;
    .btn-grp {
      margin: 15px 0 0px 0;
      width: 280px;
      text-align: right;
    }
    :deep(.el-select) {
      width: 100%;
      margin-bottom: 15px;
    }
  }
  // 排序
  .sort {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 40px;
    box-sizing: border-box;
    .sort-item {
      width: 100%;
      text-align: center;
      margin-bottom: 15px;
    }
    :deep(.el-select) {
      width: 100%;
    }
    .btn-grp {
      margin: 2px 0 0px 0;
      width: 280px;
      text-align: right;
    }
  }

  // 条件
  .condition {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    .mid {
      :deep(.el-select) {
        width: 120px;
        .el-input__inner {
          border-radius: 4px 0 0 4px;
        }
      }
      :deep(.el-select:nth-child(1)) {
        position: relative;
        left: 2px;
      }
      :deep(.el-select:nth-child(2)) {
        position: relative;
        left: 1px;
        .el-input__inner {
          border-radius: 0;
        }
      }
      :deep(.el-input.is-focus .el-input__inner) {
        border-color: #dcdfe6;
      }
      :deep(.el-select .el-input__inner:focus) {
        border-color: #dcdfe6;
      }
      :deep(.el-input__inner:focus) {
        border-color: #dcdfe6;
      }
      :deep(.input-with-select) {
        width: 240px;
        .el-input__inner {
          border-radius: 0 4px 4px 0;
        }
      }
    }
    .notes {
      width: 479px;
      margin-top: 15px;
      :deep(.el-select) {
        width: 479px;
        margin-bottom: 15px;
      }
    }
    .data-info {
      width: 479px;
      :deep(.el-select) {
        width: 479px;
        margin-bottom: 15px;
      }
    }
    .btn-grp {
      margin-top: 15px;
      width: 479px;
      text-align: right;
    }
  }

  // 统计
  .count {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    :deep(.input-with-select) {
      width: 360px;
    }
    :deep(.el-input-group__prepend) {
      background-color: #fff;
      width: 80px;
    }
    .notes {
      width: 360px;
      margin-top: 15px;
      :deep(.el-select) {
        width: 360px;
        margin-bottom: 15px;
      }
    }
    .data-info {
      width: 360px;
      :deep(.el-select) {
        width: 360px;
        margin-bottom: 15px;
      }
    }
    .btn-grp {
      margin-top: 15px;
      width: 360px;
      text-align: right;
    }
  }

  // 最大、最小
  .max-min {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    :deep(.el-input) {
      width: 240px;
      margin-bottom: 15px;
    }
    .btn-grp {
      width: 240px;
      text-align: right;
    }
  }

  .nodata {
    color: #b0b4b7;
    text-align: center;
    margin-bottom: 15px;
  }
}
</style>